'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { trpc } from '@/lib/trpc-provider'
import { copyToClipboard } from '@/lib/utils'
import { Copy, Download, Upload, RotateCcw } from 'lucide-react'

export default function JsonFormatterPage() {
  const [input, setInput] = useState('')
  const [output, setOutput] = useState('')
  const [indent, setIndent] = useState(2)
  const [error, setError] = useState('')
  const [copySuccess, setCopySuccess] = useState(false)

  const formatMutation = trpc.tools.formatJson.useMutation({
    onSuccess: (data) => {
      if (data.success) {
        setOutput(data.formatted || '')
        setError('')
      } else {
        setError(data.error || 'Unknown error')
        setOutput('')
      }
    },
    onError: (error) => {
      setError(error.message)
      setOutput('')
    }
  })

  const handleFormat = () => {
    if (!input.trim()) {
      setError('请输入JSON数据')
      return
    }
    formatMutation.mutate({ json: input, indent })
  }

  const handleCopy = async () => {
    if (output) {
      const success = await copyToClipboard(output)
      if (success) {
        setCopySuccess(true)
        setTimeout(() => setCopySuccess(false), 2000)
      }
    }
  }

  const handleClear = () => {
    setInput('')
    setOutput('')
    setError('')
  }

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const content = e.target?.result as string
        setInput(content)
      }
      reader.readAsText(file)
    }
  }

  const handleDownload = () => {
    if (output) {
      const blob = new Blob([output], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = 'formatted.json'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            JSON 格式化工具
          </h1>
          <p className="text-gray-600">
            美化和验证JSON数据，支持语法高亮和错误检测
          </p>
        </div>

        {/* Controls */}
        <div className="flex flex-wrap items-center gap-4 mb-6">
          <div className="flex items-center gap-2">
            <label className="text-sm font-medium">缩进空格:</label>
            <select 
              value={indent} 
              onChange={(e) => setIndent(Number(e.target.value))}
              className="border border-gray-300 rounded px-2 py-1 text-sm"
            >
              <option value={2}>2</option>
              <option value={4}>4</option>
              <option value={8}>8</option>
            </select>
          </div>
          
          <Button onClick={handleFormat} disabled={formatMutation.isLoading}>
            {formatMutation.isLoading ? '格式化中...' : '格式化'}
          </Button>
          
          <Button variant="outline" onClick={handleClear}>
            <RotateCcw className="w-4 h-4 mr-2" />
            清空
          </Button>
          
          <div className="relative">
            <input
              type="file"
              accept=".json,.txt"
              onChange={handleFileUpload}
              className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
            />
            <Button variant="outline">
              <Upload className="w-4 h-4 mr-2" />
              上传文件
            </Button>
          </div>
        </div>

        {/* Main Content */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Input */}
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700">
              输入 JSON
            </label>
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder='请输入JSON数据，例如: {"name": "DevBox", "version": "1.0.0"}'
              className="w-full h-96 p-4 border border-gray-300 rounded-lg font-mono text-sm resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {/* Output */}
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <label className="text-sm font-medium text-gray-700">
                格式化结果
              </label>
              <div className="flex gap-2">
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={handleCopy}
                  disabled={!output}
                >
                  <Copy className="w-4 h-4 mr-2" />
                  {copySuccess ? '已复制' : '复制'}
                </Button>
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={handleDownload}
                  disabled={!output}
                >
                  <Download className="w-4 h-4 mr-2" />
                  下载
                </Button>
              </div>
            </div>
            
            {error ? (
              <div className="w-full h-96 p-4 border border-red-300 rounded-lg bg-red-50">
                <div className="text-red-600 font-medium mb-2">错误:</div>
                <div className="text-red-700 text-sm">{error}</div>
              </div>
            ) : (
              <textarea
                value={output}
                readOnly
                placeholder="格式化后的JSON将显示在这里"
                className="w-full h-96 p-4 border border-gray-300 rounded-lg font-mono text-sm resize-none bg-gray-50"
              />
            )}
          </div>
        </div>

        {/* Features */}
        <div className="mt-12 grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="text-center p-6 bg-blue-50 rounded-lg">
            <h3 className="font-semibold text-blue-900 mb-2">语法验证</h3>
            <p className="text-blue-700 text-sm">
              自动检测JSON语法错误，提供详细的错误信息
            </p>
          </div>
          <div className="text-center p-6 bg-green-50 rounded-lg">
            <h3 className="font-semibold text-green-900 mb-2">美化格式</h3>
            <p className="text-green-700 text-sm">
              支持自定义缩进，让JSON数据更易读
            </p>
          </div>
          <div className="text-center p-6 bg-purple-50 rounded-lg">
            <h3 className="font-semibold text-purple-900 mb-2">文件支持</h3>
            <p className="text-purple-700 text-sm">
              支持上传JSON文件和下载格式化结果
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}